package org.ly817.endurance.repository;

import org.ly817.endurance.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.ly817.endurance.entity.User;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * {@link User}
 * {@link Repository}
 * Created by LuoYu on 2018/2/22.
 */
@Repository
public class UserRepository {
    /**
     * 简化操作，使用内存存储
     * ConcurrentMap 线程安全
     */
    private final ConcurrentMap<Integer,User> repository
            = new ConcurrentHashMap();

    private final static AtomicInteger idGenerator = new AtomicInteger();

    @Autowired
    private UserDao userDao;

    public boolean save(User user){
        boolean flag = false;
        Integer id = idGenerator.incrementAndGet();
        user.setId(id);
        userDao.addUser(user);
        flag = repository.put(id,user) == null;
        return flag;
    }

    public Collection<User> findAll(){
        return repository.values();
    }
}
